//
//  ELAnswerController.m
//  Test
//
//  Created by 郭洪军 on 3/26/18.
//  Copyright © 2018 Guo Hongjun. All rights reserved.
//

#import "ELAnswerController.h"
#import "TZImagePickerController.h"
#import "TZVideoPlayerController.h"
#import "TZImageManager.h"
//#import "LxGridViewFlowLayout.h"
#import "TZTestCell.h"
#import "UIView+Layout.h"

#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS

#import "Masonry.h"

@interface ELAnswerController ()<UITextViewDelegate, TZImagePickerControllerDelegate, UIImagePickerControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate> {
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    
    CGFloat _itemWH;
    CGFloat _margin;
}

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) UILabel *answerLabel;
@property (nonatomic, strong) NSMutableArray<UIImage *> *images;
@property (nonatomic, strong) NSMutableArray<NSString *> *videoPaths;

// 底部展示图片
@property (nonatomic, strong) UICollectionView *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *layout;
@property (strong, nonatomic) CLLocation *location;

@end

@implementation ELAnswerController

#pragma mark - Life Style
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    NSLog(@"%s", __FUNCTION__);
    
    _margin = 4;
    _itemWH = (self.view.tz_width - 2 * _margin - 4*2) / 3 - _margin;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = _margin;
    [self.collectionView setCollectionViewLayout:_layout];
    
    [self.collectionView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(0);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.safeAreaLayoutGuideBottom).priorityLow();
        } else {
            make.bottom.equalTo(0).priorityLow();
        }
        make.height.equalTo(self.view.tz_width / 3);
    }];
    
    [self.textView makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(0);
        make.bottom.equalTo(self.collectionView.top);
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"撰写回答";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNavigationBar];
    
    [self setupTextView];
//    [self setupAnswerLabel];
    
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    [self configCollectionView];
    
    // 监听键盘弹出与收回s
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    //
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
    });
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - UI methods.
- (void)setupNavigationBar {
    
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction:)];
    UIBarButtonItem *postItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(postAction:)];
    
    self.navigationItem.leftBarButtonItem = cancelItem;
    self.navigationItem.rightBarButtonItem = postItem;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}

- (void)setupTextView {
    
    UITextView *newTextView = [[UITextView alloc] init];
    newTextView.font = [UIFont systemFontOfSize:18];
    newTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    newTextView.scrollEnabled = YES;
    newTextView.textContainerInset = UIEdgeInsetsMake(16, 8, 16, 8);
    newTextView.returnKeyType = UIReturnKeyNext;
    newTextView.showsVerticalScrollIndicator = NO;
    newTextView.bounces = NO;
    newTextView.delegate = self;
    
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    placeHolderLabel.text = @"分享你的真实观点和经验";
    [newTextView addSubview:placeHolderLabel];
    [newTextView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    
    newTextView.dataDetectorTypes = UIDataDetectorTypeAll;
    self.textView = newTextView;
//    self.textView.inputAccessoryView = self.toolbar;
    [self.view addSubview:self.textView];
    
}

- (void)setupAnswerLabel {
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(-16, 0, [[UIScreen mainScreen] bounds].size.width, 52)];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectInset(topView.bounds, 16, 0)];
    label.textColor = [UIColor lightGrayColor];
    label.text = @"\"男到中年，不睡三觉，不去三地，不喝三酒...\"";
    [topView addSubview:label];
    
    self.answerLabel = label;
    [self.textView addSubview:topView];
    
    UIView *bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 52, [[UIScreen mainScreen] bounds].size.width, 8)];
    [topView addSubview:bottomLineView];
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = bottomLineView.bounds;
    gradientLayer.colors = @[(id)[UIColor whiteColor].CGColor,
                             (id)[UIColor colorWithRed:248.0/255 green:248.0/255 blue:248.0/255 alpha:1].CGColor];  // 设置渐变颜色
    [bottomLineView.layer addSublayer:gradientLayer];
    
}

- (UIToolbar *)toolbar {
    if (_toolbar == nil) {
        CGRect tempFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
        _toolbar = [[UIToolbar alloc] initWithFrame:tempFrame];
        
        UIBarButtonItem *photoItem = [self createItemWithImageNamed:@"photo" action:@selector(photoItemClicked:)];
        UIBarButtonItem *cameraItem = [self createItemWithImageNamed:@"video" action:@selector(cameraItemClicked:)];
        UIBarButtonItem *closeItem = [self createItemWithImageNamed:@"down" action:@selector(closeItemClicked:)];
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
     
        _toolbar.items = @[photoItem, cameraItem, spaceItem, closeItem];
        
    }
    
    return _toolbar;
}

- (UIBarButtonItem *)createItemWithImageNamed:(NSString *)imageName action:(nullable SEL)action {
    UIImage *img = [UIImage imageNamed:imageName] ;
    UIImage *imgOriginal = [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:imgOriginal style:UIBarButtonItemStylePlain target:self action:action];
    return item;
}

- (void)addImageToTextView {

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:self.textView.attributedText];
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil] ;
    textAttachment.image = [UIImage imageNamed:@"screenshot"];
    NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
    [string insertAttributedString:textAttachmentString atIndex:0];//index为用户指定要插入图片的位置
    self.textView.attributedText = string;

}

- (void)configCollectionView {
    // 如不需要长按排序效果，将LxGridViewFlowLayout类改成UICollectionViewFlowLayout即可
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    CGFloat rgb = 244 / 255.0;
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _collectionView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];

}

#pragma mark - Lazy load
- (NSMutableArray<UIImage *> *)images {
    if (!_images) {
        _images = [NSMutableArray new];
    }
    return _images;
}

- (NSMutableArray<NSString *> *)videoPaths {
    if (!_videoPaths) {
        _videoPaths = [NSMutableArray new];
    }
    return _videoPaths;
}

#pragma mark - callback methods.
- (void)photoItemClicked:(id)sender {

    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];

    imagePickerVc.allowPickingVideo = NO; // 不允许选视频
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)cameraItemClicked:(id)sender {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    
    imagePickerVc.allowPickingImage = NO; // 不允许选视频
    
    [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, id asset) {
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)closeItemClicked:(id)sender {
    [self.textView resignFirstResponder];
}

- (void)cancelAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)postAction:(id)sender {
    NSLog(@"发布消息");
    NSLog(@"text = %@", self.textView.text);
}

- (void)deleteBtnClik:(UIButton *)sender {
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
    }];
}

#pragma mark - Notification methods.
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    
    NSDictionary *userInfo = notification.userInfo;
    CGFloat height = [[UIScreen mainScreen] bounds].size.height - [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [self updateTextViewConstraintsWithHeight:height duration:duration];
}

- (void)updateTextViewConstraintsWithHeight:(CGFloat)height duration:(CGFloat)duration
{
    [self.collectionView updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(-height);
    }];
    
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
//     _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));

    // 1.打印图片名字
    [self printAssetsName:assets];
    
    for (PHAsset *asset in assets) {
        if (asset.mediaType == PHAssetMediaTypeVideo) {
            [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPreset640x480 success:^(NSString *outputPath) {
                NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
                // Export completed, send video here, send by outputPath or NSData
                // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
            } failure:^(NSString *errorMessage, NSError *error) {
                NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
            }];
        }
    }
    
    // 2.图片位置信息
    if (iOS8Later) {
        for (PHAsset *phAsset in assets) {
            NSLog(@"location:%@",phAsset.location);
        }
    }
}

#pragma mark - Private

/// 打印图片名字
- (void)printAssetsName:(NSArray *)assets {
    NSString *fileName;
    for (id asset in assets) {
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = (PHAsset *)asset;
            fileName = [phAsset valueForKey:@"filename"];
            NSLog(@"fileName = %@", fileName);
        }
    }
}

#pragma mark - UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.row == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn.png"];
        cell.deleteBtn.hidden = YES;
        cell.gifLable.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.row];
        cell.asset = _selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.gifLable.hidden = YES; // 不允许选择gif动图
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        
        imagePickerVc.allowPickingVideo = YES; // 允许选视频
        imagePickerVc.allowPickingMultipleVideo = YES;
        imagePickerVc.allowPickingImage = YES;
        // 设置目前已经选中的图片数组
        imagePickerVc.selectedAssets = _selectedAssets;
        
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        }];
        
//        [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, id asset) {
//            NSLog(@"asset = %@", asset);
//        }];
        
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    } else { // preview photos or video / 预览照片或者视频
        id asset = _selectedAssets[indexPath.row];
        BOOL isVideo = NO;
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = asset;
            isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
        }
        if (isVideo /*&& !self.allowPickingMuitlpleVideoSwitch.isOn*/) { // perview video / 预览视频
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
            vc.model = model;
            [self presentViewController:vc animated:YES completion:nil];
        } else { // preview photos / 预览照片
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
            imagePickerVc.maxImagesCount = 9;
            imagePickerVc.allowPickingOriginalPhoto = YES;
            imagePickerVc.allowPickingMultipleVideo = YES;
            imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                _selectedPhotos = [NSMutableArray arrayWithArray:photos];
                _selectedAssets = [NSMutableArray arrayWithArray:assets];
                _isSelectOriginalPhoto = isSelectOriginalPhoto;
                [_collectionView reloadData];
//                _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
            }];
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    [textView scrollRangeToVisible:NSMakeRange(textView.text.length - 1, 1)];
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSLog(@"range = %@, text = %@", NSStringFromRange(range), text);
    if ((range.location > 0) || (range.location == 0 && ![text isEqual:@""])) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    } else {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
    
    [textView scrollRangeToVisible:NSMakeRange(range.location, text.length)];
    return YES;
}

@end
